//
//  UserAccount.swift
//  sinaDemo
//
//  Created by mac on 15/12/13.
//  Copyright © 2015年 zhouxubin. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    /*
    "access_token
    "expires_in"
    "remind_in" =
    uid = 5588409
    */
    var access_token: String?
    // 后面加括号就是setter方法
    var expires_in: NSTimeInterval = 0 {
        didSet {
            // 创建这个对象的时候就设置过期日期
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    var remind_in: String?
    var uid: String?
    var name: String?
    var avatar_large: String?
    // 过期时间
    var expires_date: NSDate?
    
    // 快速创建对象
    init(dic: [String: AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dic)
        
    }
    
   override var description: String {
        let keys = ["access_token", "expires_in", "remind_in", "uid"]
        return dictionaryWithValuesForKeys(keys).description
    }
    
    // 归档解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(remind_in, forKey: "remind_in")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
    // 需要加上一个required
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        remind_in = aDecoder.decodeObjectForKey("remind_in") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    // 归档
    func save() {
        // 存入沙盒
        NSKeyedArchiver.archiveRootObject(self, toFile: accountPath)
    }
    
    // 解档, class表示类方法
    class func accoun() ->UserAccount? {
        // 判断当前时间和过期时间的大小
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount {
            // 比较过期日期和现在的日期,如果是降序那么就还没有过期
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        return nil
    }
    

}
